<?php
namespace Nanastroj;

use \Nette\Object,
	\Nette\Security\IAuthenticator,	
	\Nette\Security\AuthenticationException,	
	\Nette\Security\Identity,
 Nanastroj\UserManager;

class Authenticator extends Object implements IAuthenticator {

	private $connection; 

	public function __construct(\Nette\Database\Connection $connection) {
		$this->connection = $connection;
	}

	public function authenticate(array $credentials) {
		list($nickname, $password) = $credentials;
		
		$user = $this->connection->table('user')->where('login', $nickname)->fetch();

    if (!$user) {
			throw new AuthenticationException('Přihlašování se nezdařilo');
		}
    
		if ($user->password !== UserManager::getHashPassword($password, $user->salt)) {
			throw new AuthenticationException('Přihlašování se nezdařilo');
		}
    
    // User state
    $userStateName = $user->user_state->name;
    
    switch($userStateName){
      case 'no_active':
        throw new AuthenticationException('Učet není zatím aktivní, aktivujte jej nejprve');
        break;
      case 'blocked':
        throw new AuthenticationException('Učet byl zablokován');
        break;
      case 'deleted':
        throw new AuthenticationException('Učet byl vymazán');
        break;
    }
      
		// identity
		return new Identity($user->id, $user->role->name);
	}
	

}